package main

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

//	{
//		"result":"success",
//		"code":200,
//		"url":"http:\/\/192.168.0.103\/easyimages\/i\/2024\/03\/24\/g5k6a.jpg",
//		"srcName":"flamingos",
//		"thumb":"\/easyimages\/app\/thumb.php?img=\/i\/2024\/03\/24\/g5k6a.jpg",
//		"del":"\/easyimages\/app\/del.php?hash=TSswemg3RXRobjVMRTFhcC9IZzJvSXZKQVNmNmJqST0="
//		}
//
// 定义返回的数据结构
type UploadResponseData struct {
	Result  string `json:"result"`  //返回结果消息
	Code    int    `json:"code"`    //返回状态
	Url     string `json:"url"`     //直接访问图片地址
	SrcName string `json:"srcName"` //文件名称
	Thumb   string `json:"thumb"`   //缩略图请求地址
	Del     string `json:"del"`     //删除文件请求地址
}

func uploadHandle(w http.ResponseWriter, r *http.Request) {
	file, handler, err := r.FormFile("file")
	if err != nil {
		log.Println(err.Error())
		uploadResponseStatusError(w, r, 500, err.Error())
		return
	}
	defer file.Close()

	time_path := time.Now().Format("06/01/02/")
	path_save := "./" + files_root_path + "/" + time_path // ./files/21/03/24/
	arr := strings.Split(handler.Filename, ".")
	if len(arr) != 2 {
		uploadResponseStatusError(w, r, 500, "文件名不能有多个{.}。")
		return
	}
	filename := uuid4() + "." + arr[len(arr)-1]
	new_filename := path_save + filename

	err = os.MkdirAll(path_save, os.ModePerm)
	if err != nil {
		uploadResponseStatusError(w, r, 500, err.Error())
		log.Println(err.Error())
		return
	}
	out, err := os.Create(new_filename)
	if err != nil {
		uploadResponseStatusError(w, r, 500, err.Error())
		log.Println(err.Error())
		return
	}

	//defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		//http.Error(w, err.Error(), http.StatusInternalServerError)
		uploadResponseStatusError(w, r, 500, err.Error())
		log.Println(err.Error())
		return
	}
	DBSaveItem(handler.Filename, new_filename, (int)(handler.Size))
	uploadResponseStatus(w, r, 200, "success", files_root_path+"/"+time_path, filename, handler.Filename)
}

func uploadResponseStatusError(w http.ResponseWriter, r *http.Request, code int, message string) {
	uploadResponseStatus(w, r, code, message, "", "", "")
}

func uploadResponseStatus(w http.ResponseWriter, r *http.Request, code int, message string, path string, newNmae string, oldname string) {
	// 设置响应头类型为JSON
	w.Header().Set("Content-Type", "application/json")
	// 创建返回的数据
	response := UploadResponseData{
		Result:  message,
		Code:    code,
		Url:     r.Header.Values("Referer")[0] + path + newNmae,
		SrcName: oldname,
		Thumb:   "/app/del.php",
		Del:     "/app/del.php",
	}

	// 将数据编码为JSON
	jsonResponse, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 写入响应
	w.Write(jsonResponse)
}

func uuid4() string {
	b := make([]byte, 4)
	_, err := rand.Read(b)
	if err != nil {
		log.Fatal(err)
		return ""
	}
	uuid := fmt.Sprintf("%x", b[0:])
	return uuid
}
